<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="150px"
      v-loading="formLoading"
    >
      
      <el-form-item label="关联提货活动" prop="activityId">

        <el-select
            v-model="formData.activityId"
            class="!w-240px"
            clearable
            lable-key="name"
            placeholder="请选择提货活动"
            value-key="id"
            @keyup.enter="handleQuery"
          >
          <el-option
              v-for="item in activityList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
        </el-select>
      </el-form-item>

      <el-form-item label="请输入用户名" prop="activityId">
        <el-select
          v-model="formData.userId"
          class="!w-240px"
          clearable
          filterable
          remote
          reserve-keyword
          style="width: 100%"
          :remote-method="getUserList"
          :loading="loading"
          lable-key="name"
          placeholder="请输入用户名"
          value-key="id"
          @keyup.enter="handleUserQuery"
        >
          <el-option
            v-for="item in userList"
            :key="item.id"
            :label="item.nickname"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
     
          <el-form-item label="提货券数量" prop="number">
            <el-input-number
              v-model="formData.number"
              controls-position="right"
              :precision="0"
              class="!w-40%"
            />
          </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { PickUpUserRecordApi, PickUpUserRecordVO } from '@/api/mall/promotion/pickup/record'
import { PickUpActivityApi, PickUpActivityVO } from '@/api/mall/promotion/pickup/activity'
import * as UserApi from '@/api/member/user'
import { getListAllSimple } from '@/api/mall/trade/delivery/pickUpStore';
/** 用户领取提货记录 表单 */
defineOptions({ name: 'PickUpUserBatchRecordForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  activityId: undefined,
  number: undefined,
  userId:undefined,
})

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const queryParams = reactive({
  pageNo: 1,
  nickname :'',
  pageSize: 10,
  status: undefined,
})

const formRules = reactive({
  activityId: [{ required: true, message: '请选择活动', trigger: 'blur' }],
  number: [{ required: true, message: '请输入卡密数量', trigger: 'blur' }]

})
const formRef = ref() // 表单 Ref


const activityList = ref<PickUpActivityVO[]>([]) // 列表的数据
/** 打开弹窗 */
const open = async (type: string, id?: number) => {

  debugger
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await PickUpUserRecordApi.getPickUpUserRecordById(id)
    } finally {
      formLoading.value = false
    }
  }

  getList();
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗


/** 搜索按钮操作 */
const handleUserQuery = () => {
  queryParams.pageNo = 1
  getUserList('')
}

const userList = ref<UserApi.UserVO[]>([]) // 列表的数据

const loading = ref(true) // 列表的加载中

const getUserList = async (keyword: string) => {
  loading.value = true
  try {
    if(keyword == ''){
      return;
    }
    queryParams.nickname = keyword
    let res = await UserApi.getUserPage(queryParams)

    userList.value = res.list
  } finally {
    loading.value = false
  }
}

const getList = async () =>{
  let res = await PickUpActivityApi.getPickUpActivityPage(queryParams);
    activityList.value = res.list;
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as PickUpUserRecordVO
    if (formType.value === 'create') {
      await PickUpUserRecordApi.batchCreatePickUpUserRecord(data)
      message.success(t('common.createSuccess'))
    } else {
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    activityId: undefined,
    userId:undefined,
    number:undefined,
  }
  formRef.value?.resetFields()
}
</script>